package com.decade.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    //假设这思数据库中表
    private List<Map<String,Object>> data = new ArrayList<>();
    public AjaxController(){
       Map<String,Object> map = new HashMap<>();
       map.put("id", 100);
       map.put("name", "华为");
       map.put("remark","very good");
       data.add(map);
    }

    @GetMapping("/doAjaxStart")
    public String doAjaxStart(){
        return "result ajax data";
    }

    //@GetMapping 注解描述的方法表示只能处理Get请求方式的映射
    //@RequestMapping(value="/doAjaxGet" ,mathod=RequestMethod.GET)
    @GetMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return data;
    }

    //@RequestMapping(value="/doAjaxPost" ,mathod=RequestMethod.POST)
    //方法参数上接收Map参数，要加@RequestParam 注解。如果不加默认是拿不到参数
    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        data.add(map);
        return "save ok";
    }

    @DeleteMapping("doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable String id){
/*        for (int i=0;i<data.size();i++){
            if(data.get(i).get("id").equals(id)){
                data.remove(i);
                return "delete ok";
            }
        }*/

        Iterator<Map<String,Object>> it = data.iterator();
        while(it.hasNext()){
            Map<String, Object> map = it.next();
            if(map.get("id").equals(id)){
                it.remove();
                return "delete ok";
            }
        }
        return "delete error";
    }

    @PutMapping("/doAjaxPut")
    public String doAjaxPut(@RequestParam Map<String,Object> map){
        for (int i=0;i<data.size();i++){
            if(data.get(i).get("id").equals(map.get("id"))){
                data.get(i).put("name", map.get("name"));
                data.get(i).put("remark",map.get("remark"));
                return "update ok";
            }
        }
        return "update error";
    }
}
